//点击事件封装
(function (window){  //传入window，提高变量的查找效率
    function myQuery(selector){  //这个函数就是对外提供的接口。
        //调用这个函数的原型对象上的_init方法，并返回
        return myQuery.prototype._init(selector);
    }
    myQuery.prototype = {
        /*初始化方法，获取当前query对象的方法*/
        _init: function (selector){
            if (typeof selector == "string"){
                //把查找到的元素存入到这个原型对象上。
                this.ele = window.document.querySelector(selector);
                //返回值其实就是原型对象。
                return this;
            }
        },
        /*单击事件：
         * 为了规避click的300ms的延迟，自定义一个单击事件
         * 触发时间：
         *   当抬起手指的时候触发
         *   需要判断手指落下和手指抬起的事件间隔，如果小于500ms表示单击时间。
         *
         *   如果是大于等于500ms，算是长按时间
         * */
        tap: function (handler){
            this.ele.addEventListener("touchstart", touchFn);
            this.ele.addEventListener("touchend", touchFn);

            var startTime,
                endTime;

            function touchFn(e){
                e.preventDefault()
                switch (e.type){
                    case "touchstart":
                        startTime = new Date().getTime();
                        break;
                    case "touchend":
                        endTime = new Date().getTime();
                        if (endTime - startTime < 500){
                            handler.call(this, e);
                        }
                        break;
                }
            }
        },
        /**
         * 长按
         * @param handler
         */
        longTag: function (handler){
            this.ele.addEventListener("touchstart", touchFn);
            this.ele.addEventListener("touchmove", touchFn);
            this.ele.addEventListener("touchend", touchFn);
            var timerId;

            function touchFn(e){
                switch (e.type){
                    case "touchstart" :  //500ms之后执行
                        timerId = setTimeout(function (){
                            handler.call(this, e);
                        }, 500)
                        break;
                    case "touchmove" :
                        //如果中间有移动也清除定时器
                        clearTimeout(timerId)
                        break;
                    case "touchend" :
                        //如果在500ms之内抬起了手指，则需要定时器
                        clearTimeout(timerId);
                        break;
                }
            }
        },
        /**
         * 左侧滑动。
            记录手指按下的左边，在离开的时候计算 deltaX是否满足左滑的条件
         *
         */
        slideLeft: function (handler){
            this.ele.addEventListener("touchstart", touchFn);
            this.ele.addEventListener("touchend", touchFn);
            var startX, startY, endX, endY;

            function touchFn(e){
                e.preventDefault();
                var firstTouch = e.changedTouches[0];
                switch (e.type){
                    case "touchstart":
                        startX = firstTouch.pageX;
                        startY = firstTouch.pageY;
                        break;
                    case "touchend":
                        endX = firstTouch.pageX;
                        endY = firstTouch.pageY;
//x方向移动大于y方向的移动，并且x方向的移动大于25个像素，表示在向左侧滑动
                        if (Math.abs(endX - startX) >= Math.abs(endY - startY) && startX - endX >= 25){
                            handler.call(this, e);
                        }
                        break;
                }
            }
        },
        /**
         * 右侧滑动。
         *
         */
        rightLeft: function (e){
            //TODO:
        }
    }
    window.$ = window.myQuery = myQuery;
})(window);

var multipleCheck = function(t){//t为初始化时传入的参数
	//参数验证
	//el,leval,multip,checkdata,template;
	//template:btncolor,titlebg,linecolor,checkicon;
	var that = this
	var templatedefault = {btncolor:'#d28',titlebg:'#d1d1d1',linecolor:'#d1d1d1',checkicon:'default',boxbg:'#fff',maskbg:{bgcolor:'#000',opacity:'0.6'}};

	var internalAttribute = t;//传入参数集合
	var domel = internalAttribute.el||'';//传入dom
	var leval = internalAttribute.leval||'1';//层级默认一级
	var multip = internalAttribute.multip||false;//是否多选，默认单选
	var checkdata = internalAttribute.checkdata||[];//传入数据,默认为空
	var template = internalAttribute.template||templatedefault;//使用模板,
	var multipparameter = {show:false}
	var twoul;
	var status = {leval1:'',leval2:'',leval3:'',firstcheckindex:'',twocheckindex:'',threecheckindex:[],firstind:[],twoind:'',checkstatus:false};
	var selectdata = [];
	var temselectdata = {};

	$(domel).tap(function(){
		if(multipparameter.show == true){
			return false;
		}
		createEl()
	})
	
	//创建dom
	function createEl(){
		var html = '<div id="" class="checkdialog"><div class="checktitle"><span class="checkchangebtn">取消</span> 标题 <span class="checkconfimbtn" onclick="multiplecheck.removeEl()">确定</span></div><div id="checkcont" class="checkcont"><div id="checkcontitem1" class="checkcontitem"><ul class="checkcontul" id="checkcontul"></ul></div><div id="checkconttwo" class=""><ul id="checkcontultwo"></ul></div><div id="checkcontthree" class=""><ul id="checkcontulthree"></ul></div></div></div>'
		var dbody = document.body;
		var ddiv = document.createElement('div');
		ddiv.setAttribute('id','checkbox');
		dbody.appendChild(ddiv);
		ddiv.innerHTML = html;
		multipparameter.show = true;
		datapush()
	}
	
	//删除dom
	this.removeEl = function(){
		var removedom = document.getElementById('checkbox');
		
		document.body.removeChild(removedom)
		
		multipparameter.show = false;
		subbtnfn()
	}
	var removeLi = function(leval){
		if(leval == 1)
		var elthree = document.getElementById('checkcontthree');
		var elulthree = document.getElementById('checkcontulthree');
		elthree.setAttribute('class','')
		elulthree.innerHTML = ''
		if(leval == 2)
		console.log("2")
	}	
	
	this.liclick=function(likey){
		if(likey==status.firstcheckindex){
			return false;
		}
		//初始化列表
		removeLi(1)
		//渲染当前选中项
		statusAddBg(1,likey)
		//执行事件
		status.leval1 = likey//保存层级索引
		if(leval==1){
			that.levalOneFn()
		}
		if(leval!=1){
			outselectdata(likey)
			temselectdata = {id:likey,name:checkdata[likey].name,city:[]};
			var eltwo = document.getElementById('checkconttwo');
			eltwo.setAttribute('class','checkcontitem');
			datapushtwo()
		}
	}
	
	//二级列表事件
	this.twoliclick = function(twolikey){
		
		//渲染当前选中项
		statusAddBg(2,twolikey)
		
		status.leval2 = twolikey
		if(leval==2){
			that.levalTwoFn()
		}
		if(leval==3){
			//levalTwoFn()
			
			var eltwo = document.getElementById('checkcontthree');
			eltwo.setAttribute('class','checkcontitem');
			datapushthree()
			//生成二级JSON数据
			if(temselectdata.city[status.twoind]){
				if(temselectdata.city[status.twoind].county==''){
					delete temselectdata.city[status.twoind];
					temselectdata.city.pop();
				}
			};
			var twodata = {id:twolikey,name:checkdata[status.firstcheckindex].city[status.twocheckindex].name,county:[]};
			temselectdata.city.push(twodata)
			status.twoind = temselectdata.city.length-1;//保存索引			
			//清空三级临时数据
			status.threecheckindex = [];
		}
		
	}
	//leval1事件
	this.levalOneFn = function(ind){
		console.log("1")
	}
	//leval2事件
	this.levalTwoFn = function(ind){
		console.log("2")
	}
	//leval3事件
	this.levalThreeFn = function(ind){
		//渲染当前选中项
		statusAddBg(3,ind)
	}
	
	//数据渲染
	function datapush(){
		var checkcontbox = document.getElementById('checkcontul');
		var lidata = '';
		for(var i = 0; i < checkdata.length; i++){
			lidata = lidata + '<li onclick=multiplecheck.liclick('+i+')>'+checkdata[i].name+'<span class="levalonetip"></span></li>'
		}
		checkcontbox.innerHTML = lidata
		jroll = new JRoll('#checkcontitem1')
	}
	//渲染二级数据
	function datapushtwo(){
		//二级数据渲染
		var checkcontbox = document.getElementById('checkcontultwo');
		var lidatatwo = '';
		for(var i = 0; i < checkdata[status.leval1].city.length; i++){
			lidatatwo = lidatatwo + '<li onclick=multiplecheck.twoliclick('+i+')>'+checkdata[status.leval1].city[i].name+'</li>'
		}
		checkcontbox.innerHTML = lidatatwo
		jroll2 = new JRoll('#checkconttwo')
		jroll2.scrollTo(0, 0, 100, true)
	}
	//渲染三级数据
	function datapushthree(){
		//三级数据渲染
		var checkcontbox = document.getElementById('checkcontulthree');
		var lidatathree = '';
		for(var i = 0; i < checkdata[status.leval1].city[status.leval2].county.length; i++){
			lidatathree = lidatathree + '<li onclick=multiplecheck.levalThreeFn('+i+')>'+checkdata[status.leval1].city[status.leval2].county[i]+'</li>'
		}
		checkcontbox.innerHTML = lidatathree
		jroll3 = new JRoll('#checkcontthree')
		jroll3.scrollTo(0, 0, 100, true)
	}
	//一级遍历
	
	
	//状态渲染方法
	function statusAddBg(leval,ind){
		if(leval==1){
			var childrenel = document.getElementById('checkcontul').children;
			if(status.firstcheckindex!==''){
				childrenel[status.firstcheckindex].style.backgroundColor = '#FFFFFF';
			}
			status.firstcheckindex = ind;
			childrenel[ind].style.backgroundColor = '#e1e1e1'
		}
		if(leval==2){
			var childrenel = document.getElementById('checkcontultwo').children;
			if(status.twocheckindex!==''){
				childrenel[status.twocheckindex].style.backgroundColor = '#FFFFFF';
			}
			status.twocheckindex = ind;
			childrenel[ind].style.backgroundColor = '#e1e1e1'
		}
		if(leval==3){
			var childrenel = document.getElementById('checkcontulthree').children;
			
			//childrenel[status.threecheckindex].style.backgroundColor = '#FFFFFF';
			if(status.threecheckindex.indexOf(ind) >= 0 ){
				var i = status.threecheckindex.indexOf(ind);
				status.threecheckindex.splice(i,1)
				childrenel[ind].style.backgroundColor = '#FFFFFF';
				removedata(i)
				return false;
			}else{
				status.threecheckindex.push(ind);
				console.log(status.threecheckindex)
				pushdata()
				childrenel[ind].style.backgroundColor = '#e1e1e1'
			}
		}
	}
	
	//选择项组成数组
	function pushdata(){
		if(leval==1){
			console.log("1")
		}
		if(leval==2){
			console.log("2")
		}
		if(leval==3){
			var countylist = [];
			for(var c = 0; c < status.threecheckindex.length; c++){
				var name = checkdata[status.firstcheckindex].city[status.twocheckindex].county[status.threecheckindex[c]]
				var county = {id:status.threecheckindex[c],name:name}
				countylist.push(county)
			}
			temselectdata.city[status.twoind].county = countylist;
			status.checkstatus = true;
			console.log(JSON.stringify(temselectdata))
		}
	}
	//取消所选
	function removedata(i){
		if(leval==1){
			console.log("1")
		}
		if(leval==2){
			console.log("2")
		}
		if(leval==3){
			delete temselectdata.city[status.twoind].county[i];
			temselectdata.city[status.twoind].county.pop();
			return false;
		}
	}
	//数据输出方法
	function outselectdata(likey){
		if(status.firstind.indexOf(likey)<0){//不存在
			if(status.checkstatus){//验证三级是否有数据 真----插入
				selectdata.push(temselectdata);
				status.firstind.push(temselectdata.id);
				temselectdata = [];
			}
				
		}else{
			if(status.checkstatus){//验证三级是否有数据 真----插入
				delete selectdata[status.firstind.indexOf(likey)];
				selectdata.pop();
				selectdata.push(temselectdata);
				status.firstind.push(temselectdata.id);
				temselectdata = [];
			}
		}		
	}
	//提交事件
	function subbtnfn(){
		var likey = status.firstcheckindex;
		var domsplit = domel.split('.');
		var domtype = document.getElementById(domsplit[1]).tagName;
		outselectdata(likey)
		if(domtype == 'INPUT'){
			document.getElementById(domsplit[1]).value = JSON.stringify(selectdata);
		}
		if(domtype == 'DIV'){
			document.getElementById(domsplit[1]).innerText = JSON.stringify(selectdata);
		}
	}
}


//加滚动效果、状态效果、生成数组
//重新渲染数据-----判断是否有数据-----获取索引，得到数据，赋值给temselectdata-----添加状态